/*
 * Copyright Aristool AG Switzerland
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */

package org.opprua.dss.application;

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import org.opprua.tidy.gens.GClass;
import org.opprua.tidy.gens.GMethod;
import org.opprua.tidy.util.XReader;
import org.w3c.dom.Element;

/**
 * TODO: add Java doc
 * 
 * Prepared for first commit: 23.02.2007
 * 
 * @author Lin Li
 */
public class DProvider extends XReader {

  private DConfigData configData;
  private Map<String, DCall> methods = new TreeMap<String, DCall>();

  @Override
  public void read(Element e) {
    configData = collectOne(e, "configData", DConfigData.class);
  }

  public void register(DCall c) {
    String k = c.getMethod() + ":" + c.getParamType();
    DCall s = methods.get(k);
    if (s != null) {
      if (!s.getReturnType().equals(c.getReturnType()))
        throw new Error("Provider definition: unmatching return type for " + getName() + "." + k);
    } else {
      methods.put(k, c);
    }
  }

  public String getName() {
    return getAttribute("name");
  }

  public String getType() {
    return getAttribute("type");
  }

  public String getPackage() {
    return getAttribute("package");
  }

  public String getSourceDir() {
    return getAttribute("sourceDir");
  }

  public DConfigData getConfigData() {
    return configData;
  }

  public void generateInterface() {
    if (!RUtil.has(getType())) return;

    GClass g = new GClass(getType());
    g.setModifiers("public interface");
    g.setPackage(getPackage());

    for (Iterator<String> iter = methods.keySet().iterator(); iter.hasNext();) {
      DCall c = methods.get(iter.next());
      String r = c.getReturnType();
      if(r == null || r.equals("null")) {
        r = "Object";
      }
      GMethod m = g.newMethod("public", c.getMethod(), "org.opprua.dss.data.Result<" + r + ">");
      m.setIsAbstract();
      String pType = c.getParamType();
      if (pType != null && pType.length() > 0) {
        m.addParameter(pType, "incomming");
      }
    }
    g.dump(getSourceDir());
  }
}
